﻿create PROCEDURE Sync.SP_LoanCancellingDebtAttachments_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @LoanCancellingDebtAttachments_Temp TABLE 
		(
			LoanCancellingDebtAttachmentID UniqueIdentifier,
			[LoanCancellingDebtID] uniqueidentifier,
				[Attachment] uniqueidentifier,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @LoanCancellingDebtAttachments_Temp 
	   SELECT	Tbl.Col.value('LoanCancellingDebtAttachmentID[1]','uniqueidentifier') LoanCancellingDebtAttachmentID,
                Tbl.Col.value('LoanCancellingDebtID[1]', 'uniqueidentifier') [LoanCancellingDebtID],
Tbl.Col.value('Attachment[1]', 'uniqueidentifier') [Attachment],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/LoanCancellingDebtAttachments') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[LoanCancellingDebtAttachments] ([LoanCancellingDebtAttachmentID],[LoanCancellingDebtID],[Attachment])
	SELECT t.[LoanCancellingDebtAttachmentID],t.[LoanCancellingDebtID],t.[Attachment]
	FROM  @LoanCancellingDebtAttachments_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.LoanCancellingDebtAttachments_Tracking s
        WHERE t.LoanCancellingDebtAttachmentID = s.LoanCancellingDebtAttachmentID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[LoanCancellingDebtAttachments]
	SET [LoanCancellingDebtAttachments].[LoanCancellingDebtID] = t.[LoanCancellingDebtID],[LoanCancellingDebtAttachments].[Attachment] = t.[Attachment] 
	FROM [dbo].[LoanCancellingDebtAttachments] s JOIN @LoanCancellingDebtAttachments_Temp t 
    ON t.LoanCancellingDebtAttachmentID = s.LoanCancellingDebtAttachmentID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.LoanCancellingDebtAttachments_Tracking r
				  WHERE t.LoanCancellingDebtAttachmentID = r.LoanCancellingDebtAttachmentID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[LoanCancellingDebtAttachments]
    FROM @LoanCancellingDebtAttachments_Temp t JOIN [dbo].[LoanCancellingDebtAttachments] s
    ON t.LoanCancellingDebtAttachmentID = s.LoanCancellingDebtAttachmentID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END











